<template>
	<div class="date-picker">
		<uni-datetime-picker v-if="type == 'date'" type="date" :border="false" :clear-icon="clearable" :disabled="disabled" :readonly="readonly" v-model="modelValue" @change="changePicker" :placeholder="placeholder" />
		<uni-datetime-picker :readonly="readonly" v-else-if="type == 'datetime'" :border="false" type="datetime" :clear-icon="clearable" :disabled="disabled" v-model="modelValue" @change="changePicker" :placeholder="placeholder" />
		<uni-datetime-picker :readonly="readonly" v-else-if="type == 'daterange'" :border="false" type="daterange" :clear-icon="clearable" :disabled="disabled" v-model="modelValue" @change="changePicker" :placeholder="placeholder" :rangeSeparator="rangeSeparator" :start-placeholder="startPlaceholder" :end-placeholder="endPlaceholder" />
		<uni-datetime-picker :readonly="readonly" v-else-if="type == 'datetimerange'" :border="false" type="datetimerange" :clear-icon="clearable" :disabled="disabled" v-model="modelValue" @change="changePicker" :placeholder="placeholder" :rangeSeparator="rangeSeparator" :start-placeholder="startPlaceholder" :end-placeholder="endPlaceholder" />
		<div class="month" v-else-if="type == 'month'">
			<div class="input">
				<uni-icons class="icon" type="calendar" color="#c4c4cf" size="22" @click="open"></uni-icons>
				<div @click="open">{{ monthValue ? monthValue : placeholder }}</div>
				<uni-icons class="close" v-if="!readonly" :type="monthValue ? 'close' : ''" color="#c4c4cf" size="18" @click="close"></uni-icons>
			</div>
			<u-picker mode="time" v-model="show" :params="paramsMonth" @confirm="onConfirm"></u-picker>
		</div>
		<div class="month" v-else-if="type == 'year'">
			<div class="input">
				<uni-icons class="icon" type="calendar" color="#c4c4cf" size="22" @click="open"></uni-icons>
				<div @click="open">{{ yearValue ? yearValue : placeholder }}</div>
				<uni-icons class="close" v-if="!readonly" :type="yearValue ? 'close' : ''" color="#c4c4cf" size="18" @click="close"></uni-icons>
			</div>
			<u-picker mode="time" v-model="show" :params="paramsYear" @confirm="onConfirm"></u-picker>
		</div>
		<div class="week" v-else-if="type == 'week'">
			<div class="input">
				<uni-icons class="icon" type="calendar" color="#c4c4cf" size="22" @click="weekOpen"></uni-icons>
				<div @click="weekOpen">{{ weekValue ? weekValue : placeholder }}</div>
				<uni-icons class="close" v-if="!readonly" :type="weekValue ? 'close' : ''" color="#c4c4cf" size="18" @click="close"></uni-icons>
			</div>
			<uni-popup ref="popup" type="bottom">
				<view class="popup">
					<view class="picker-btn">
						<view class="left" @click="cancel">取消</view>
						<view class="right" @click="confirm">确定</view>
					</view>
					<picker-view :indicator-style="indicatorStyle" :value="selectValue" class="picker-view" @change="bindChange">
						<picker-view-column>
							<view v-for="(item, index) in years" :key="index" class="item">{{ item }}年</view>
						</picker-view-column>
						<picker-view-column v-show="current">
							<view v-for="(item, index) in months" :key="index" class="item">{{ item }}月</view>
						</picker-view-column>
						<picker-view-column v-show="!current">
							<view v-for="(item, index) in weeks" :key="index" class="item">{{ `第${index + 1}周(` + item + ")" }}</view>
						</picker-view-column>
					</picker-view>
				</view>
			</uni-popup>
		</div>
	</div>
</template>

<script>
import dayjs from "dayjs"
let myDate = new Date()
let year = myDate.getFullYear()
export default {
	name: "vDatePicker",
	model: {
		prop: "value",
		event: "update:value",
	},
	props: {
		value: {
			type: [String, Object, Array, Number, Date],
			default: "",
		},
		disabled: {
			type: Boolean,
			default: false,
		},
		readonly: {
			type: Boolean,
			default: false,
		},
		clearable: {
			type: Boolean,
			default: false,
		},
		format: {
			type: String,
			default: "yyyy-MM-dd",
		},
		placeholder: {
			type: String,
			default: "请选择日期",
		},
		type: {
			type: String,
			default: "date",
		},
		// 分隔符
		rangeSeparator: {
			type: String,
			default: "-",
		},
		startPlaceholder: {
			type: String,
			default: "开始日期",
		},
		endPlaceholder: {
			type: String,
			default: "结束日期",
		},
	},
	data() {
		return {
			show: false,
			monthValue: "",
			paramsMonth: {
				year: true,
				month: true,
				day: false,
				hour: false,
				minute: false,
				second: false,
			},
			yearValue: "",
			paramsYear: {
				year: true,
				month: false,
				day: false,
				hour: false,
				minute: false,
				second: false,
			},
			indicatorStyle: `height: ${Math.round(uni.getSystemInfoSync().screenWidth / (750 / 100))}px;`,
			// selectValue: [5, this.month - 1, 0],
			weekValue: "",
			dateObj: {},
			current: false,
			// myDate: "",
			years: [],
			months: [],
			week: "",
			showWeek: "第1周",
			payload: {},
			bindChangeList: [],
		}
	},

	computed: {
		modelValue: {
			get() {
				return this.value
			},
			set(val) {
				this.$emit("update:value", val)
			},
		},
		weeks() {
			const ONE_DAY = 24 * 3600 * 1000
			let firstDay = new Date(year + "/01/01").getDay() == 0 ? 7 : new Date(year + "/01/01").getDay()
			let weeklist = []
			let firstweekday = ""
			let endweekday = new Date(year + "/12/28").getTime()
			if (firstDay > 4) {
				firstweekday = new Date(year + "/01/01").getTime() + (8 - firstDay) * ONE_DAY
			} else if (firstDay <= 4) {
				firstweekday = new Date(year + "/01/01").getTime() - (firstDay - 1) * ONE_DAY
			}
			for (let i = 0; i < 54; i++) {
				let numWeek = i * 7 * ONE_DAY
				let firstday = firstweekday + numWeek
				let endday = firstday + 6 * ONE_DAY
				if (firstday <= endweekday) {
					weeklist.push(`${dayjs(firstday).format("MM/DD")}-${dayjs(endday).format("MM/DD")}`)
				}
			}
			return weeklist
		},
		selectValue: {
			get() {
				return [5, this.month - 1, 0]
			},
			set(val) {
				// year = this.years[val[0]]
				// this.month = this.months[val[1]]
				// this.week = this.weeks[val[2]]
				// this.showWeek = "第" + (val[2] + 1) + "周"
				// this.$emit("update:value", val)
			},
		},
		month: {
			get() {
				return myDate.getMonth() + 1
			},
			set(val) {
				// this.myDate.setMonth(val - 1)
			},
		},
	},
	mounted() {
		this.week = this.weeks[0]
	},
	created() {
		this.getInit()
		this.monthValue = this.modelValue
		this.yearValue = this.modelValue
		this.weekValue = this.modelValue
	},

	methods: {
		changePicker(e) {
			this.$emit("update:value", e)
		},
		open() {
			if (this.disabled || this.readonly) return
			this.show = true
		},
		weekOpen() {
			if (this.disabled || this.readonly) return
			this.$refs.popup.open()
			console.log(this.years, "years")
		},
		onConfirm(e) {
			if (this.type == "month") {
				this.monthValue = `${e.year}-${e.month}`
				this.$emit("update:value", this.monthValue)
			} else if (this.type == "year") {
				this.yearValue = `${e.year}`
				this.$emit("update:value", this.yearValue)
			}
		},
		close() {
			this.monthValue = ""
			this.yearValue = ""
			this.weekValue = ""
		},
		getInit() {
			for (let i = myDate.getFullYear() - 5; i <= myDate.getFullYear(); i++) {
				this.years.push(i)
			}

			for (let i = 1; i <= 12; i++) {
				this.months.push(i)
			}
		},
		bindChange(e) {
			const val = e.detail.value
			year = this.years[val[0]]
			this.month = this.months[val[1]]
			this.week = this.weeks[val[2]]
			this.showWeek = "第" + (val[2] + 1) + "周"
		},
		cancel() {
			this.$refs.popup.close()
		},
		confirm() {
			if (this.current) {
				// 月
				this.month = this.month > 10 ? this.month : "0" + this.month
				this.payload = {
					startTime: year + "-" + this.month + "-" + "01",
					endTime: year + "-" + this.month + "-" + "31",
					showTime: year + "-" + this.month,
				}
			} else {
				// 周
				this.selectValue[0] = this.years.findIndex(item => item == year)
				this.selectValue[1] = this.month - 1
				this.selectValue[2] = this.weeks.findIndex(item => item == this.week)
				const [firstWeek, lastWeek] = this.week.split("-").map(item => item.replace("/", "-"))
				this.payload = {
					startTime: year + "-" + firstWeek,
					endTime: year + "-" + lastWeek,
					showTime: year + "-" + this.showWeek,
				}
			}
			this.dateObj = this.payload
			this.weekValue = this.payload.showTime
			this.$emit("update:value", this.dateObj.startTime)

			this.$refs.popup.close()
			console.log(this.years, "years")
		},
		getYearWeek(a, b, c) {
			// a:年份，b:月份，c:日期
			var date1 = new Date(a, parseInt(b) - 1, c), //当前日期
				date2 = new Date(a, 0, 1), //当年第一天
				// d是当前日期是今年第多少天
				d = Math.round((date1.valueOf() - date2.valueOf()) / 86400000)
			// d + 当前年的第一天的周差距的和在除以7就是本年第几周
			return Math.ceil((d + (date2.getDay() + 1 - 1)) / 7)
		},
	},
}
</script>
<style lang="scss" scoped>
.date-picker {
	width: 100%;
}
.input {
	padding: 0 10rpx;
	// border: 1px solid #e5e5e5;
	border-radius: 8rpx;
	display: flex;
	align-items: center;
	gap: 10rpx;
	color: #74726b;
	.close {
		margin-left: auto;
	}
}
.popup {
	height: fit-content;
	width: 100%;
	background: #fff;
}

.picker-btn {
	display: flex;
	height: 100upx;
	width: 100%;
	line-height: 100upx;
	background: #fff;
	font-size: 34upx;
	z-index: 1;
	border-bottom: 1rpx solid #f8f8f8;

	.left {
		flex: 1;
		color: #0076ff;
		padding-left: 40upx;
		box-sizing: border-box;
	}

	.right {
		flex: 1;
		text-align: right;
		padding-right: 40upx;
		color: #fe4533;
		box-sizing: border-box;
	}
}

picker-view {
	width: 100%;
	height: 500rpx;
	display: relative;
}
.item {
	line-height: 100rpx;
	text-align: center;
}
</style>
